package com.sitanyun.merchant.guide.frament.view.fragment;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.adapter.ShopEnterAdapter;
import com.sitanyun.merchant.guide.base.BaseFragment;
import com.sitanyun.merchant.guide.bean.EnterShopDialsBean;
import com.sitanyun.merchant.guide.bean.QueryBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.frament.presenter.impl.ShtopFPresenterImpl;
import com.sitanyun.merchant.guide.frament.presenter.inter.IShtopFPresenter;
import com.sitanyun.merchant.guide.frament.view.inter.IShtopFView;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceshop;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import okhttp3.Call;

/**
 * /**
 * 浏览次数
 * 贾宗霖
 * 222222
 * A simple {@link Fragment} subclass.
 */
public class EnterFragment extends BaseFragment implements IShtopFView {

    @BindView(R.id.users)
    TextView users;
    @BindView(R.id.tv_screen)
    TextView tvScreen;
    @BindView(R.id.shar_rv)
    RecyclerView sharRv;
    @BindView(R.id.shopenter_list)
    ListView shopenterList;
    @BindView(R.id.scen_fh)
    ImageView scenFh;
    @BindView(R.id.sw_sharcount)
    SwipeRefreshLayout swSharcount;
    private PopupWindow popupWindow;
    private ShopEnterAdapter shopEnterAdapter;
    // 分页
    private int offset = 1;
    private List<EnterShopDialsBean.DataBean.RecordsBean> orderbeanlist;
    private IShtopFPresenter mIShtopFPresenter;
    @Override
    public int getLayoutId() {
        return R.layout.fragment_enter;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mIShtopFPresenter = new ShtopFPresenterImpl(this);
        offset = 1;
        initokhttps("100");
    }

    @Override
    public void initView() {
        tvScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scenFh.animate().setDuration(500).rotation(180).start();
                initpopu(v);
            }
        });
        orderbeanlist = new ArrayList<>();
        //创建管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        sharRv.setLayoutManager(layoutManager);
        shopEnterAdapter = new ShopEnterAdapter(getActivity(),"2");
        sharRv.setAdapter(shopEnterAdapter);
        shopEnterAdapter.notifyDataSetChanged();

        //刷新
        swSharcount.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                offset = 1;
                initokhttps("100");
            }
        });
//        //加载更多
        shopEnterAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                offset++;
                initokhttps("100");
            }
        });
    }

    private void initpopu(View v) {
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.shopenter_items, null);
        Button onemoth = (Button) contentView.findViewById(R.id.onemoth);
        Button twomoth = (Button) contentView.findViewById(R.id.twomoth);
        Button threemoth = (Button) contentView.findViewById(R.id.threemoth);
        Button toyear = (Button) contentView.findViewById(R.id.toyear);
        Button all = (Button) contentView.findViewById(R.id.all);
        onemoth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvScreen.setText("近1个月");
                offset = 1;
                popupWindow.dismiss();
                initokhttps("1");
                shopEnterAdapter.notifyDataSetChanged();
            }
        });

        twomoth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvScreen.setText("近2个月");
                offset = 1;
                popupWindow.dismiss();
                initokhttps("2");
                shopEnterAdapter.notifyDataSetChanged();
            }
        });
        threemoth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvScreen.setText("近3个月");
                offset = 1;
                popupWindow.dismiss();
                initokhttps("3");
                shopEnterAdapter.notifyDataSetChanged();
            }
        });
        toyear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvScreen.setText("今年");
                offset = 1;
                popupWindow.dismiss();
                initokhttps("12");
                shopEnterAdapter.notifyDataSetChanged();
            }
        });
        all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvScreen.setText("全部");
                offset = 1;
                popupWindow.dismiss();
                initokhttps("100");
                shopEnterAdapter.notifyDataSetChanged();
            }
        });
        popupWindow = new PopupWindow(contentView,
                330, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //   Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                scenFh.animate().setDuration(500).rotation(0).start();
            }
        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.baise));

        // 设置好参数之后再show
        popupWindow.showAsDropDown(v);
        //      popupWindow.showAtLocation(tvScreen, Gravity.BOTTOM,0,0);

    }

    private void initokhttps(String s) {
        if (SharedPreferenceshop.getStringData("type").equals("1")) {
          //  mIShtopFPresenter.getquery(s,"1");
            OkHttpUtils.get().url(Urls.storepage)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                    .addParams("sortType", "2")
                    .addParams("queryMonth", s)
                    .addParams("current", String.valueOf(offset))
                    .addParams("size", "10")
                    .build().execute(new StringCallbacks() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    swSharcount.setRefreshing(false);
                }

                @Override
                public void onResponse(String response, int id) {
                    swSharcount.setRefreshing(false);
                    EnterShopDialsBean enterBean = new Gson().fromJson(response, EnterShopDialsBean.class);
                    if (enterBean.getCode()==0){
                        users.setText("共"+enterBean.getData().getTotal()+"导购已参与");
                        if (offset == 1) {
                            orderbeanlist.clear();
                            shopEnterAdapter.setNewData(enterBean.getData().getRecords());
                            orderbeanlist.addAll(enterBean.getData().getRecords());
                            shopEnterAdapter.notifyDataSetChanged();
                        }else {
                            //orderbeanlist.addAll(orderBean.getData());
                            //底部没有数据时
                            if (enterBean.getData().getRecords().isEmpty()) {
                                shopEnterAdapter.loadMoreEnd();

                            } else {
                                //滑动加载数据
                                List<EnterShopDialsBean.DataBean.RecordsBean> data1 = enterBean.getData().getRecords();
                                orderbeanlist.addAll(data1);
                                shopEnterAdapter.addData(data1);
                                shopEnterAdapter.notifyDataSetChanged();
                                shopEnterAdapter.loadMoreComplete();

                            }
                        }
                    }

                }
            });
        } else {
           // mIShtopFPresenter.getquery(s,"2");
            OkHttpUtils.get().url(Urls.enterprisepage)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                    .addParams("sortType", "2")
                    .addParams("queryMonth", s)
                    .addParams("current", String.valueOf(offset))
                    .addParams("size", "10")
                    .build().execute(new StringCallbacks() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    swSharcount.setRefreshing(false);
                }

                @Override
                public void onResponse(String response, int id) {
                    swSharcount.setRefreshing(false);
                    EnterShopDialsBean enterBean = new Gson().fromJson(response, EnterShopDialsBean.class);
                    if (enterBean.getCode()==0){
                        users.setText("共"+enterBean.getData().getTotal()+"导购已参与");
                        if (offset == 1) {
                            orderbeanlist.clear();
                            shopEnterAdapter.setNewData(enterBean.getData().getRecords());
                            orderbeanlist.addAll(enterBean.getData().getRecords());
                            shopEnterAdapter.notifyDataSetChanged();
                        }else {
                            //orderbeanlist.addAll(orderBean.getData());
                            //底部没有数据时
                            if (enterBean.getData().getRecords().isEmpty()) {
                                shopEnterAdapter.loadMoreEnd();
                            } else {
                                //滑动加载数据
                                List<EnterShopDialsBean.DataBean.RecordsBean> data1 = enterBean.getData().getRecords();
                                orderbeanlist.addAll(data1);
                                shopEnterAdapter.addData(data1);
                                shopEnterAdapter.notifyDataSetChanged();
                                shopEnterAdapter.loadMoreComplete();

                            }
                        }
                    }
                }
            });
        }
    }


    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IShtopFView.RESPONSE_ONE) {
            QueryBean queryBean = (QueryBean) response;
            if (queryBean.getCode() == 0) {
                users.setText("共"+queryBean.getData()+"用户已参与");
            }
        }
    }
}
